<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Alban Technologies. Written by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/login.php";

if ($login['username'] == "")
{
  header ("location: ./");
  exit;
}

$connection = db_open ();

/* Create the XML feed */
if (isset ($_POST['path']))
{
  $xmlfeed = "<page><title>Page title</title><fields>";
  
  $result = mysql_query ("SELECT fields FROM ".db_maketablename ($table_templates)." WHERE id='{$_POST['template']}'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      /* Prepare the XML parser and parse the data */
      $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".$row['fields'];     
      $xmlres = xml_parser_create ("utf-8");
      xml_parse_into_struct ($xmlres, $xmldata, $values);
      xml_parser_free ($xmlres);
      
      /* Walk through the tags */
      $i = 0;
      while ($values[$i])
        {
          if ($values[$i]['level'] == 2 && strcasecmp ($values[$i]['tag'], "field") == 0 && isset ($values[$i]['attributes']['NAME']))
            {
              $name = $values[$i]['attributes']['NAME'];
              $label = $values[$i]['attributes']['LABEL'];
              $label = htmlentities ($label, ENT_COMPAT, "UTF-8", false);
              $xmlfeed .= "<$name>$label</$name>";
            }
          $i++;
        }
    }
  mysql_free_result ($result);

  $xmlfeed .= "</fields></page>";
  
  $path = str_replace (" ", "_", $_POST['path']);
  while (substr ($path, 0, 1) == "/")
    $path = substr ($path, 1);
  
  /* Now add the page in the database */
  mysql_query ("INSERT INTO ".db_maketablename ($table_pages)." (path, version, starttime, endtime, template, xmlfeed) VALUES ('".mysql_real_escape_string ($path)."', '1', '0', '0', '{$_POST['template']}', '".mysql_real_escape_string ($xmlfeed)."')");
  $pid = mysql_insert_id ($connection);
}

db_close ($connection);
header ("location:$app_adminpath/?p=site&pid=$pid");
exit;
?>
